﻿#region License
/* ---------------------------------------------------------------- *
 *
 * This file is part of the Xcoordination Application Space
 * ("XcoAppSpace") http://www.xcoordination.com
 *
 * Copyright (C) 2009 Xcoordination http://www.xcoordination.com
 *
 * XcoAppSpace is free software; you can redistribute it and/or
 * modify it under the terms of version 2 of the GNU General
 * Public License as published by the Free Software Foundation.
 *
 * XcoAppSpace is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/
 * or write to the Free Software Foundation, Inc., 51 Franklin
 * Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * ---------------------------------------------------------------- */
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using XcoAppSpaces.Contracts.PortWiring;
using XcoAppSpaces.Core.Ports;

namespace XcoAppSpaces.Serialization.Binary
{
	class PortSerializationSurrogate : ISerializationSurrogate
	{
	    private readonly IPortWirer portWirer;

		public PortSerializationSurrogate(IPortWirer portWirer)
        {
            this.portWirer = portWirer;
        }

		public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
		{
            var portInfo = portWirer.GetPortSerializationInfo((IPort)obj);
            info.AddValue("addr", portInfo.RemoteAddress);
			info.AddValue("guid", portInfo.RemotePortGuid);
		}

		public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
		{
			var addr = (string)info.GetValue("addr", typeof(string));
			var guid = (Guid)info.GetValue("guid", typeof(Guid));
			var portInfo = new XcoPortSerializationInfo(addr,guid);
			obj = Activator.CreateInstance(obj.GetType()); //make new instance because the deserialized one is not usable
            portWirer.WireRemotePort((IPort)obj, portInfo);
		    return obj;
		}
	}
}
